#!/usr/bin/env bash
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/apps/functions"
source "$PLUGIN_AVAILABLE_PATH/config/functions"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x

cmd-logs-failed() {
  declare desc="shows the last failed deploy logs"
  declare cmd="logs:failed"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1"
  local DOKKU_SCHEDULER

  if [[ -z "$APP" ]]; then
    local INSTALLED_APPS=$(dokku_apps)
    for app in $INSTALLED_APPS; do
      fn-logs-failed-single "$app" | tee || true
    done
  else
    fn-logs-failed-single "$APP"
  fi
}

fn-logs-failed-single() {
  declare desc="shows the last failed deploy logs for an app"
  declare APP="$1"
  local DOKKU_SCHEDULER

  dokku_log_info2_quiet "${APP} failed deploy logs"
  DOKKU_SCHEDULER=$(get_app_scheduler "$APP")
  plugn trigger scheduler-logs-failed "$DOKKU_SCHEDULER" "$APP"
}

cmd-logs-failed "$@"
